//
//  MainViewController.swift
//  Weibo
//
//  Created by 李振兴 on 15/10/14.
//  Copyright © 2015年 李振兴. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    @objc private func clickComposedButton(){
        print("click")
        let vc:UIViewController
        if UserAccountViewModel.sharedUserAccount.isLogon {
            vc = ComposeViewController()
        }else{
            vc = OAuthViewController()
        }
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view .addSubview(btn)
        
        addChildViewControllers()
        addButton()
    } 
    override func viewWillAppear(animated: Bool) {
        // 会创建 tabBar 中的所有控制器对应的按钮！
        super.viewWillAppear(animated)
        
        // 将撰写按钮弄到最前面
        tabBar.bringSubviewToFront(btn)
    }

    private lazy var btn:UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
   
}
//MARK:设置界面
extension MainViewController{
    /// 添加中间按钮
    private func addButton(){
        
        // 1. 添加按钮
        tabBar.addSubview(btn)
        
        // 2. 调整按钮
        let count = childViewControllers.count
        // 让按钮宽一点点，能够解决手指触摸的容错问题
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        btn.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        // 3. 添加监听方法
        btn.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
    }
    /// 添加所有的控制器
    private func addChildViewControllers() {
        
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    /// 添加控制器
    func addChildViewController(vc: UIViewController,title:String,imageName:String) {
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nv = UINavigationController(rootViewController: vc)
        addChildViewController(nv)
    }
}